package app.auto.runner.base.utility.base;

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMinMax implements InputFilter {
    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    public InputFilterMinMax setMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
        return this;
    }

    public InputFilterMinMax setSign(String sign) {
        this.sign = sign;
        return this;
    }

    String sign = "";

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            if (sign.equals(dest.toString() + source)) {
                return source;
            }
            if ((dest.toString() + source.toString()).startsWith("#")) {
                if (source.length() > 0) {
                    int input = Integer.parseInt(source.toString());
                    if (isInRange(min, max, input))
                        return source;
                }
            }
            int input = 0;
            if (dest.toString().equals("")) {

            } else {
                input += Integer.parseInt(dest.toString());
            }
            if (source.toString().equals("")) {

            } else {
                input += Integer.parseInt(source.toString());
            }


            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) {
        }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}